﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.InvoiceManagements;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.InvoiceManagements;

namespace Reporting.API.Application.CommandHandler.InvoiceManagements
{
    /// <summary>
    /// 修改开票
    /// </summary>
    public class UpdateInvoiceManagementCommandHandler : IRequestHandler<UpdateInvoiceManagementCommand, ApiResult>
    {
        private readonly IInvoiceManagementRepository _invoiceManagementRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateInvoiceManagementCommandHandler> _logger;

        public UpdateInvoiceManagementCommandHandler(ILogger<UpdateInvoiceManagementCommandHandler> logger, IMapper mapper, IInvoiceManagementRepository invoiceManagementRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _invoiceManagementRepository = invoiceManagementRepository;
        }


        public async Task<ApiResult> Handle(UpdateInvoiceManagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询开票
                var InvoiceManagements = await _invoiceManagementRepository.GetAsync(x => x.Invoicemanagementid == request.Invoicemanagementid);

                if (InvoiceManagements == null)
                {
                    return ApiResult.Fail("修改当前数据不存在", StatusCodeEnum.BadRequest);
                }


                // 更新开票
                var InvoiceManagementresult = _mapper.Map(request, InvoiceManagements);
                await _invoiceManagementRepository.UpdateAsync(InvoiceManagementresult);


                return ApiResult.Success(StatusCodeEnum.Success);


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改开票修改失败");
                throw;
            }
        }
    }
}
